<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>获取图片主色例子</title>
  </head>

  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
    <img
      id="image"
      src="https://grocery-cdn.huaban.com/file/6ccf5020-b653-11ed-ab85-ef9549ca1204.jpg"
      alt="一张图片"
      crossorigin="anonymous"
    />

    <div id="box" class="box"></div>
    <div id="boxs" class="box"></div>

    <script>
      //获取图片
      const img = document.querySelector("#image");
      //获取a框
      const a = document.getElementById("box");
      const b = document.getElementById("boxs");
      //准备回去颜色
      const colorThief = new ColorThief();

      // 传入一个 Image 对象
      function colorfulImg(img) {
        let canvas = document.createElement("canvas"),
          context = canvas.getContext && canvas.getContext("2d"),
          height,
          width,
          length,
          data,
          i = -4,
          blockSize = 5,
          count = 0,
          rgb = { r: 0, g: 0, b: 0 };

        height = canvas.height = img.height;
        width = canvas.width = img.width;
        context.drawImage(img, 0, 0);
        data = context.getImageData(0, 0, width, height).data;
        length = data.length;

        // 计算像素点平均颜色值
        while ((i += blockSize * 4) < length) {
          ++count;
          rgb.r += data[i];
          rgb.g += data[i + 1];
          rgb.b += data[i + 2];
        }

        rgb.r = ~~(rgb.r / count);
        rgb.g = ~~(rgb.g / count);
        rgb.b = ~~(rgb.b / count);

        return rgb;
      }

      // 监听图片加载完成事件，获取主色并设置为背景色
      window.onload = () => {
        //const rgb = colorfulImg(image);
        //a.style.backgroundColor = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
      };

      if (img.complete) {
        const aa = colorfulImg(img);
        console.log(aa);
        a.style.backgroundColor = `rgb(${aa.r}, ${aa.g}, ${aa.b})`;

        const bb = colorThief.getColor(img);
        console.log(bb);
        b.style.backgroundColor = `rgb(${bb[0]}, ${bb[1]}, ${bb[2]})`;
      } else {
        image.addEventListener("load", function () {
          const aa = colorfulImg(img);
          console.log(aa);
          a.style.backgroundColor = `rgb(${aa.r}, ${aa.g}, ${aa.b})`;
          const bb = colorThief.getColor(img);
          console.log(bb);
          b.style.backgroundColor = `rgb(${bb[0]}, ${bb[1]}, ${bb[2]})`;
        });
      }
    </script>
    <style>
      .box {
        width: 300px;
        height: 300px;
        border: 1px solid tomato;
      }
    </style>
  </body>
</html>
